#include<iostream>
#include<pthread.h>
#include<vector>
#include<assert.h>
#include<string.h>
#include<unistd.h>

using namespace std;
#define NUM 5
pthread_mutex_t mut=PTHREAD_MUTEX_INITIALIZER;//全局初始化互斥量
pthread_cond_t cond=PTHREAD_COND_INITIALIZER;//全局初始化条件变量
int ticket=1000;
void* start_routine(void* args)
{
    string str=static_cast<const char*>(args);

    while(true)
    {
         pthread_mutex_lock(&mut);//加锁
         if(ticket>0)
    {
 pthread_cond_wait(&cond,&mut);//让调用函数线程在条件变量出阻塞等待
        //到这里说明在条件变量处阻塞等待的线程已经被唤醒
        cout<<str<<"-> ticket: "<<ticket<<endl;
        ticket--;
    }else
    {
     pthread_mutex_unlock(&mut);//解锁
     break;
    }       
      pthread_mutex_unlock(&mut);//解锁
    }

}


int main()
{
    pthread_t dt[NUM];//数组存储多个线程id
    for(int i=0;i<NUM;i++)
    {
        char * name=new char[64];
        snprintf(name,64,"thread:%d",i);//设置线程名字
       int n= pthread_create(&dt[i],nullptr,start_routine,(void*)name);
    assert(n==0);
    }
   
   while(true)
   {
    usleep(500000);//1-1000-1000000
    pthread_cond_signal(&cond);//给条件变量发信号，唤醒处在条件变量处的阻塞的一个线程
    pthread_cond_broadcast(&cond);////给条件变量发信号，唤醒处在条件变量处的阻塞的全部线程
    cout<<"main thread wake up one thread"<<endl;
   }

   for(int i=0;i<NUM;i++)
   {
    pthread_join(dt[i],nullptr);//回收线程
   }
    return 0;
}